// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "ComHook.h"
#include "Config.h"

enum HOOK_STATUS { NOT_INIT, INITIALISING, INIT_SUCCESS, INIT_FAILED };

HOOK_STATUS g_iInitStatus = NOT_INIT;
HMODULE g_hModule = NULL;
DWORD g_dwMainThreadId = NULL;
DWORD g_dwInitThreadId = NULL;

DWORD WINAPI InitialisationThread(LPVOID lpParameter)
{
	g_dwInitThreadId = GetCurrentThreadId();
	Sleep(4000);
	BOOL bIinitSuccess = ReadConfiguration();
	if (bIinitSuccess)
	{
		g_iInitStatus = INITIALISING;
		HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_dwMainThreadId);
		SuspendThread(hThread);
		InitialiseHooks(g_hModule);
		ResumeThread(hThread);
		CloseHandle(hThread);
	}
	g_iInitStatus = bIinitSuccess ? INIT_SUCCESS : INIT_FAILED;
	/*if (!bIinitSuccess)
		FreeLibrary(g_hModule);*/
	return 0;
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
	DWORD dwThreadId;

	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		g_hModule = hModule;
		g_dwMainThreadId = GetCurrentThreadId();
		CloseHandle(CreateThread(NULL, 0, InitialisationThread, GetCurrentThread(), 0, &dwThreadId));
		break;
	case DLL_THREAD_ATTACH:
		while (g_iInitStatus == INITIALISING)
			Sleep(200);
		break;
	case DLL_THREAD_DETACH:
		break;
	case DLL_PROCESS_DETACH:
		/*if (g_iInitStatus == INIT_FAILED && g_dwInitThreadId == GetCurrentThreadId())
		{
			ExitThread(0);
		}
		else*/ if (g_iInitStatus == INIT_SUCCESS)
		{
			UninitialiseHooks();
			Sleep(1000);
		}
		break;
	}
	return TRUE;
}

